import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/date_utils.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/view/mine/setting/view_input_edit.dart';
import 'package:flutter_chip/widget/view_loading.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provide/provide.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

///编辑资料

class EditUserPage extends StatefulWidget {
  @override
  _EditUserPageState createState() => _EditUserPageState();
}

class _EditUserPageState extends State<EditUserPage> {
  User user;
  String msg = "加载中...";
  bool loading = false;
  bool isEdit = false;
  File imgHead;
  File imgBg;

  //1头像选择 2背景图选择
  int type = 0;

  //输入框编辑类型
  int editType = -1;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    user = Provide.value<User>(context);
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Theme.of(context).canvasColor,
        leading: IconButton(
            icon: Icon(Icons.arrow_back),
            onPressed: () {
              if (isEdit) {
                showMsgDialog(context);
              } else {
                Routers.router.pop(context);
              }
            }),
        actions: <Widget>[
          FlatButton(
              onPressed: !isEdit ? null : () => _submit(),
              child: Text(
                '保存',
                style: TextStyle(fontSize: 16),
              ),
              disabledTextColor: Color(0xff999999))
        ],
        automaticallyImplyLeading: false,
        title: Text(
          '编辑资料',
          style: TextStyle(fontSize: 18),
        ),
      ),
      body: ProgressDialog(
        msg: msg,
        loading: loading,
        child: CustomScrollView(slivers: <Widget>[
          _headerWidget(),
          SliverToBoxAdapter(child: Divider(height: 1)),
          _nickWidget(),
          SliverToBoxAdapter(child: Divider(height: 1)),
          _bgWidget(),
          SliverToBoxAdapter(child: Divider(height: 1)),
          _sexWidget(),
          SliverToBoxAdapter(child: Divider(height: 1)),
          _birthWidget(),
          SliverToBoxAdapter(child: Divider(height: 1)),
          _localWidget(),
          SliverToBoxAdapter(child: Divider(height: 1)),
          _addressWidget(),
          SliverToBoxAdapter(child: Divider(height: 1)),
          _profileWidget(),
        ]),
      ),
    );
  }

  ///头像
  Widget _headerWidget() {
    Widget imageWidget;
    if (null != imgHead) {
      imageWidget = Image.file(imgHead, fit: BoxFit.fill);
      print("加载本地图片");
    } else {
      if (null == user || null == user.imgUrl) {
        imageWidget = Image.asset(Comm.IMG_USER_BG, fit: BoxFit.fill);
        print("加载默认图片");
      } else {
        imageWidget = CachedNetworkImage(
            imageUrl: Api.getUrl(user.imgUrl), fit: BoxFit.fill);
        print("加载网络图片${Api.getUrl(user.imgUrl)}");
      }
    }
    return SliverToBoxAdapter(
        child: Container(
            color: Colors.white,
            width: double.maxFinite,
            height: 48,
            padding: EdgeInsets.only(left: 10),
            child: Row(mainAxisSize: MainAxisSize.max, children: <Widget>[
              Container(
                  width: 70, child: Text('头像', style: TextStyle(fontSize: 16))),
              Expanded(child: Container()),
              Container(
                  width: 36,
                  height: 36,
                  child: ClipRRect(
                      borderRadius: BorderRadius.circular(10),
                      child: imageWidget)),
              IconButton(
                  icon: Icon(Icons.keyboard_arrow_right,
                      color: Color(0xffCCCCCC)),
                  onPressed: () {
                    showModalBottomSheet(
                        backgroundColor: Colors.transparent,
                        context: context,
                        builder: (builder) {
                          type = 1;
                          return _choicePic();
                        });
                  })
            ])));
  }

  ///昵称
  Widget _nickWidget() {
    bool isVip = null != user && user.vip == 1;
    return SliverToBoxAdapter(
      child: Container(
        color: Colors.white,
        width: double.maxFinite,
        height: 48,
        padding: EdgeInsets.only(left: 10),
        child: Row(mainAxisSize: MainAxisSize.max, children: <Widget>[
          Container(
              width: 70, child: Text('昵称', style: TextStyle(fontSize: 16))),
          Expanded(child: Container()),
          Text((null == user || null == user.userName) ? "" : user.userName,
              style: TextStyle(color: Color(0xff999999))),
          IconButton(
              icon: Icon(Icons.keyboard_arrow_right, color: Color(0xffCCCCCC)),
              onPressed: () async {
                if (!isVip &&
                    (null != user && !user.userName.startsWith("用户_"))) {
                  Toast.show("修改昵称仅对会员开放~");
                  return;
                }
                final result = await Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => InputPage(max: 10)),
                );
                setState(() {
                  isEdit = true;
                  user.userName = result;
                });
              })
        ]),
      ),
    );
  }

  ///背景图
  Widget _bgWidget() {
    Widget imageWidget;
    if (null != imgBg) {
      imageWidget = Image.file(imgBg, fit: BoxFit.fill);
      print("加载本地图片");
    } else {
      if (null == user || null == user.headBg) {
        imageWidget = Image.asset(Comm.IMG_USER_BG, fit: BoxFit.fill);
        print("加载默认图片");
      } else {
        imageWidget = CachedNetworkImage(
            imageUrl: Api.getUrl(user.headBg), fit: BoxFit.fill);
        print("加载网络图片${Api.getUrl(user.headBg)}");
      }
    }
    bool isVip = null != user && user.vip == 1;
    return SliverToBoxAdapter(
      child: Container(
        color: Colors.white,
        width: double.maxFinite,
        height: 48,
        padding: EdgeInsets.only(left: 10),
        child: Row(mainAxisSize: MainAxisSize.max, children: <Widget>[
          Container(
              width: 70, child: Text('背景图', style: TextStyle(fontSize: 16))),
          Expanded(child: Container()),
          Container(
              width: 36,
              height: 36,
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(10), child: imageWidget)),
          IconButton(
              icon: Icon(Icons.keyboard_arrow_right, color: Color(0xffCCCCCC)),
              onPressed: () {
                if (!isVip) {
                  Toast.show("个性背景仅对会员开放~");
                  return;
                }
                showModalBottomSheet(
                    backgroundColor: Colors.transparent,
                    context: context,
                    builder: (builder) {
                      type = 2;
                      return _choicePic();
                    });
              })
        ]),
      ),
    );
  }

  ///性别
  Widget _sexWidget() {
    String sex = "";
    if (null != user && null != user.sex) {
      sex = user.sex;
    }
    return SliverToBoxAdapter(
      child: Container(
        color: Colors.white,
        width: double.maxFinite,
        height: 48,
        padding: EdgeInsets.only(left: 10),
        child: Row(mainAxisSize: MainAxisSize.max, children: <Widget>[
          Container(
              width: 70, child: Text('性别', style: TextStyle(fontSize: 16))),
          Expanded(child: Container()),
          Text(sex, style: TextStyle(color: Color(0xff999999))),
          IconButton(
            icon: Icon(Icons.keyboard_arrow_right, color: Color(0xffCCCCCC)),
            onPressed: () => _choiceSexDialog(context),
          )
        ]),
      ),
    );
  }

  ///生日
  Widget _birthWidget() {
    return SliverToBoxAdapter(
        child: Container(
            color: Colors.white,
            width: double.maxFinite,
            height: 48,
            padding: EdgeInsets.only(left: 10),
            child: Row(mainAxisSize: MainAxisSize.max, children: <Widget>[
              Container(
                  width: 70, child: Text('生日', style: TextStyle(fontSize: 16))),
              Expanded(child: Container()),
              Text((null == user || null == user.birth) ? "" : user.birth,
                  style: TextStyle(color: Color(0xff999999))),
              IconButton(
                  icon: Icon(Icons.keyboard_arrow_right,
                      color: Color(0xffCCCCCC)),
                  onPressed: () {
                    print("点击选择生日");
                    choiceDateTime(context);
                  })
            ])));
  }

  ///常住
  Widget _localWidget() {
    return SliverToBoxAdapter(
        child: Container(
            color: Colors.white,
            width: double.maxFinite,
            height: 48,
            padding: EdgeInsets.only(left: 10),
            child: Row(mainAxisSize: MainAxisSize.max, children: <Widget>[
              Container(
                  width: 70, child: Text('常住', style: TextStyle(fontSize: 16))),
              Expanded(child: Container()),
              Text((null == user || null == user.local) ? "" : user.local,
                  style: TextStyle(color: Color(0xff999999))),
              IconButton(
                  icon: Icon(Icons.keyboard_arrow_right,
                      color: Color(0xffCCCCCC)),
                  onPressed: () {})
            ])));
  }

  ///个人简介
  Widget _profileWidget() {
    return SliverToBoxAdapter(
        child: Container(
            color: Colors.white,
            width: double.maxFinite,
            height: 48,
            padding: EdgeInsets.only(left: 10),
            child: Row(mainAxisSize: MainAxisSize.max, children: <Widget>[
              Container(
                  width: 100,
                  child: Text('个人简介', style: TextStyle(fontSize: 16))),
              Expanded(
                child: Text(
                  (null == user || null == user.introduce)
                      ? '他很懒，什么也没留下'
                      : user.introduce,
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.end,
                ),
              ),
              IconButton(
                  icon: Icon(Icons.keyboard_arrow_right,
                      color: Color(0xffCCCCCC)),
                  onPressed: () async {
                    final result = await Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => InputPage(max: 50),
                      ),
                    );
                    setState(() {
                      isEdit = true;
                      user.introduce = result;
                    });
                  })
            ])));
  }

  ///收货地址
  Widget _addressWidget() {
    return SliverToBoxAdapter(
      child: Container(
        color: Colors.white,
        width: double.maxFinite,
        height: 48,
        padding: EdgeInsets.only(left: 10),
        child: Row(mainAxisSize: MainAxisSize.max, children: <Widget>[
          Container(
              width: 100, child: Text('收货地址', style: TextStyle(fontSize: 16))),
          Expanded(child: Container()),
          IconButton(
              icon: Icon(Icons.keyboard_arrow_right, color: Color(0xffCCCCCC)),
              onPressed: () {
                Routers.router.navigateTo(context, Routers.PAGE_ADDRESS,
                    transition: TransitionType.inFromRight);
              })
        ]),
      ),
    );
  }

  ///选择图片对话框
  Widget _choicePic() {
    return Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
      Container(
          width: double.maxFinite,
          margin: EdgeInsets.all(10),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(6)),
          child: Column(children: <Widget>[
            FlatButton(onPressed: _openCamera, child: Text('拍照')),
            Divider(height: 1, color: Color(0xffBBBBBB)),
            FlatButton(onPressed: _openAlbum, child: Text('从相册中选择'))
          ])),
      Container(
          width: double.maxFinite,
          margin: EdgeInsets.only(left: 10, right: 10, bottom: 10),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(6)),
          child: FlatButton(
            onPressed: () => Navigator.pop(context),
            child: Text('取消'),
          ))
    ]);
  }

  ///打开相册
  Future _openAlbum() async {
    print('打开相册');
    Navigator.pop(context);
    AssetPicker.pickAssets(context,
            maxAssets: 1, themeColor: Theme.of(context).accentColor)
        .then((List<AssetEntity> assets) {
      assets.forEach((AssetEntity asset) async {
        File image = await asset.file;
        _uploadImage(image);
      });
    });
  }

  ///打开相机
  void _openCamera() async {
    Navigator.pop(context);
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    if (null != image) {
      _uploadImage(image);
    }
  }

  ///信息提示对话框
  void showMsgDialog(BuildContext context) {
    showCupertinoDialog(
        context: context,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text("提示"),
            content: Column(
              children: <Widget>[
                SizedBox(
                  height: 10,
                ),
                Align(
                  child: Text(
                    "您已经编辑内容，但尚未保存，您确定要退出吗？",
                    style: TextStyle(fontSize: 16),
                  ),
                  alignment: Alignment(0, 0),
                ),
              ],
            ),
            actions: <Widget>[
              CupertinoDialogAction(
                child: Text("取消"),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              CupertinoDialogAction(
                child: Text("确定"),
                onPressed: () {
                  Navigator.pop(context);
                  Routers.router.pop(context);
                },
              ),
            ],
          );
        });
  }

  ///性别选择
  void _choiceSexDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text(
              "请选择性别",
              style: TextStyle(fontWeight: FontWeight.w600),
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                RadioListTile(
                    value: "",
                    title: Text("保密"),
                    groupValue: user.sex,
                    onChanged: (value) {
                      setState(() {
                        isEdit = true;
                        user.sex = value;
                      });
                      Navigator.pop(context);
                    }),
                RadioListTile(
                    value: "男",
                    title: Text("男"),
                    groupValue: user.sex,
                    onChanged: (value) {
                      setState(() {
                        isEdit = true;
                        user.sex = value;
                      });
                      Navigator.pop(context);
                    }),
                RadioListTile(
                    value: "女",
                    title: Text("女"),
                    groupValue: user.sex,
                    onChanged: (value) {
                      setState(() {
                        isEdit = true;
                        user.sex = value;
                      });
                      Navigator.pop(context);
                    }),
              ],
            ),
          );
        });
  }

  ///选择日期
  void choiceDateTime(BuildContext context) async {
    DatePicker.showDatePicker(context,
        showTitleActions: true,
        minTime: DateTime(1990, 1, 1),
        maxTime: DateTime.now(), onConfirm: (date) {
      print('confirm $date');
      setState(() {
        isEdit = true;
        user.birth = DateUtil.getDateStrByDateTime(date,
            format: DateFormat.YEAR_MONTH_DAY);
      });
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  ///上传图片
  Future _uploadImage(File file) async {
    if (null == file) return;
    isEdit = true;
    setState(() {
      msg = "上传中...";
      loading = true;
    });
    List<File> files = List();
    files.add(file);
    Http.upload(Api.URL_UPLOAD, files, successCallBack: (data) {
      Toast.show("上传成功");
      setState(() {
        loading = false;
        if (type == 1) {
          imgHead = file;
          user.imgUrl = json.decode(data)[0]["path"];
        } else {
          imgBg = file;
          user.headBg = json.decode(data)[0]["path"];
        }
      });
    }, errorCallBack: (errorMsg) {
      setState(() {
        loading = false;
      });
    });
  }

  ///保存修改
  Future _submit() async {
    Map<String, String> params = Map();
    if (null == user) {
      return;
    }
    if (null == user.userName && user.userName.isEmpty) {
      Toast.show("用户昵称不能为空");
      return;
    }
    params["imgUrl"] = user.imgUrl;
    params["userName"] = user.userName;
    if (null != user.headBg) {
      params["headBg"] = user.headBg;
    }
    if (null != user.sex && user.sex.isNotEmpty) {
      params["sex"] = user.sex;
    }
    if (null != user.birth && user.birth.isNotEmpty) {
      params["birth"] = user.birth;
    }
    if (null != user.introduce && user.introduce.isNotEmpty) {
      params["introduce"] = user.introduce;
    }
    if (null != user.local && user.local.isNotEmpty) {
      params["local"] = user.local;
    }
    setState(() {
      msg = "保存中...";
      loading = true;
    });
    Http.post(Api.URL_USER_UPDATE, params: params, successCallBack: (data) {
      Toast.show("保存成功");
      setState(() {
        isEdit = false;
        loading = false;
        user.update(User.fromJson(json.decode(data)));
      });
      Routers.router.pop(context);
    }, errorCallBack: (error) {
      Toast.show(error);
      setState(() {
        loading = false;
      });
    });
  }
}
